$(function() {
    var map = new AMap.Map("container", {
        resizeEnable: true,
        zoomEnable: true,
        center: [120.197706, 30.214253], // 初始化地图中心点 https://lbs.amap.com/demo/javascript-api/example/map/get-mapzoom
        zoom: 11
    });

    var scale = new AMap.Scale();
    map.addControl(scale);

    var arrivalRange = new AMap.ArrivalRange();
    var x, y, t, vehicle = "sub";
    var workAddress = undefined,
        workMarker;
    var rentMarkerArray = []; // 租房信息
    var polygonArray = [];
    var amapTransfer;
    var workplacePosition = [];
    var rentData;
    // 创建覆盖物群组，并将 marker 传给 OverlayGroup
    var disLimit = 1000;
    var housesource = 'anjuke';
    var curMarkerLngLat = undefined;

    var copyPL = $('#priceL').val()
    var copyPH = $('#priceH').val()


    var infoWindow = new AMap.InfoWindow({
        offset: new AMap.Pixel(0, -30)
    });

    // 1 工作地点输入 自动补全
    var auto = new AMap.Autocomplete({
        input: "work-location",
        citylimit: true, // 限制在当前城市搜索
        city: '杭州'
    });
    AMap.event.addListener(auto, "select", function(e) {
        workAddress = e.poi.name;

    });

    $('#work-location').on('blur', function() {
        // 如果输入框有值
        if ($(this).val()) {
            auto.search($(this).val(), function(status, result) {
                if (status === 'complete') {
                    workAddress = result.tips[0].name;
                    $('#work-location').val(workAddress);
                    // console.log(workAddress);
                    loadWorkLocation();
                    $("#btn_submit").removeAttr("disabled");
                } else {
                    console.log('没有这个地方');
                }

            })
        }
    })

    // function workLocationSelected(e) {
    //     workAddress = e.poi.name;
    //     loadWorkLocation();
    // }

    // 给工作地点添加标记
    function loadWorkMarker(x, y, locationName) {
        workMarker = new AMap.Marker({
            map: map,
            title: locationName,
            icon: 'http://webapi.amap.com/theme/v1.3/markers/n/mark_r.png',
            position: [x, y]

        });
    }

    // function loadWorkRange(x, y, t, color, v) {
    //     arrivalRange.search([x, y], t, function(status, result) {
    //         if (result.bounds) {
    //             for (var i = 0; i < result.bounds.length; i++) {
    //                 var polygon = new AMap.Polygon({
    //                     map: map,
    //                     fillColor: color,
    //                     fillOpacity: "0.4",
    //                     strokeColor: color,
    //                     strokeOpacity: "0.8",
    //                     strokeWeight: 1
    //                 });
    //                 polygon.setPath(result.bounds[i]);
    //                 polygonArray.push(polygon);
    //             }
    //         }
    //     }, {
    //         policy: v // 出行方式
    //     });
    // }

    // 清空工作地点
    function delWorkLocation() {
        if (polygonArray)
            map.remove(polygonArray);
        if (workMarker)
            map.remove(workMarker);

        polygonArray = [];
    }

    // 根据工作地点进行初始化
    function loadWorkLocation() {
        delWorkLocation();
        // 地址解析器
        var geocoder = new AMap.Geocoder({
            city: "杭州",
            radius: 1000
        });

        geocoder.getLocation(workAddress, function(status, result) {
            if (status === "complete" && result.info === 'OK') {
                var geocode = result.geocodes[0];
                x = geocode.location.getLng();
                y = geocode.location.getLat();
                workplacePosition = geocode.location;
                loadWorkMarker(x, y);
                // loadWorkRange(x, y, 60, "#3f67a5", vehicle);
                map.setZoomAndCenter(12, [x, y]); // 地图缩放至指定级别并以指定点为地图显示中心点
            }
        })
    }


    // 2 更改交通方式
    $('#sub_bus, #sub').on('click', function() {
        vehicle = this.value;
        // loadWorkLocation()
        if (amapTransfer)
            $('.info-win span').click()
    })

    // 3 更改距离要求
    $('#dis_none, #dis_1, #dis_2, #dis_3').on('click', function() {
        disLimit = parseInt(this.value);
        // loadWorkLocation()
    })


    // 5 更改金额限制   L < H
    // $('#priceL, #priceH').on('blur', function() {

    // })

    // 6 更改房源
    $('#hs_1, #hs_2, #hs_3').on('click', function() {
        closeInfoWindow();
        delRentLocation();

        housesource = parseInt(this.value);
        switch (parseInt(this.value)) {
            case 1:
                housesource = 'lianjia'
                break;
            case 2:
                housesource = '58'
                break;
            case 3:
                housesource = 'anjuke'
                break;
            default:
                alert('no support house source!')
        }
    })

    // 7 提交申请
    $('#btn_submit').on('click', function() {
        var pL = $('#priceL').val()
        var pH = $('#priceH').val()
        if (pL > pH) {
            alert('最低价格必须小于最高价格！')
            $('#priceL').val(copyPL)
            $('#priceH').val(copyPH)
            return false
        }
        copyPL = pL
        copyPH = pH

        $(this).attr("disabled", "true");

        data = {
            wp: workAddress,
            disLimit: disLimit,
            pL: pL,
            pH: pH
        };
        // $.getJSON('http://127.0.0.1:5000/lianjia', function(data) {
        $.get('http://127.0.0.1:5000/' + housesource, data, function(e) {
            // alert(11)
            rentData = e;
            loadRentLocation();
        })
    })

    // 距离限制
    function computeDis(p1, p2) {
        return Math.round(p1.distance(p2));
    }

    // 根据租房地址，在地图上添加标记
    function addMarkerByAddress(address) {
        var geocoder = new AMap.Geocoder({
            city: "杭州",
            radius: 1000 // 半径
        });
        geocoder.getLocation(address[1], function(status, result) {
            if (status === "complete" && result.info === 'OK') {
                var geocode = result.geocodes[0];

                // 距离判断
                if (computeDis(workplacePosition, geocode.location) > disLimit) {
                    return -1;
                }

                // 新建标记点
                rentMarker = new AMap.Marker({
                    map: map,
                    title: address[1],
                    icon: 'http://webapi.amap.com/theme/v1.3/markers/n/mark_b.png',
                    position: [geocode.location.getLng(), geocode.location.getLat()]
                });
                rentMarkerArray.push(rentMarker);

                // 信息窗
                var info = document.createElement("div");
                info.className = "info-win";

                // 头部
                var top = document.createElement("div");
                var closeX = document.createElement("img");
                top.className = "infotop";
                closeX.src = "https://webapi.amap.com/images/close2.gif";
                closeX.onclick = closeInfoWindow;
                top.appendChild(closeX);
                info.appendChild(top);

                // 房屋展示
                var show = document.createElement('div')
                show.className = 'houseshow'
                show.innerHTML = "<img src='" + address[4] + "'>";
                info.appendChild(show)

                // 房屋信息
                content = [];
                content.push("<h3>" + address[3] + "</h3>");
                content.push("<a target = '_blank' href='" + "https:// hz.lianjia.com" + address[2] + "'>" + address[0] + "</a>");

                var middle = document.createElement("div");
                middle.className = "housemsg";
                middle.style.backgroundColor = 'white';
                middle.innerHTML = content.join(" "); //houseshow
                info.appendChild(middle);

                // 点击导航
                var tran = document.createElement("span");
                tran.className = "tran-btn"
                tran.innerHTML = '&gt;&gt;导航'
                tran.onclick = transferTo;

                info.appendChild(tran)

                // 添加事件 点击显示信息窗
                rentMarker.on('click', function(e) {
                    curMarkerLngLat = new AMap.LngLat(e.lnglat.getLng(), e.lnglat.getLat())
                        // console.log($(this));
                    var infoWindow = new AMap.InfoWindow({
                        isCustom: true, //使用自定义窗体
                        content: info,
                        offset: new AMap.Pixel(16, -45)
                    });

                    infoWindow.open(map, e.target.getPosition());
                });


            }
        })
    }

    //关闭信息窗体
    function closeInfoWindow() {
        map.clearInfoWindow();

        // 如果打开了导航，关闭导航
        if (amapTransfer)
            amapTransfer.clear();

        curMarkerLngLat = undefined;
        $('.transfer-panel').innerHTML = '';
    }

    // 导航
    function transferTo() {
        // console.log('导航');
        if (amapTransfer)
            amapTransfer.clear();

        options = {
            map: map,
            policy: AMap.TransferPolicy.LEAST_TIME,
            city: "杭州市",
            panel: 'transfer-panel'
        };

        switch (vehicle) {
            case 'sub':
                amapTransfer = new AMap.Transfer(options);

                amapTransfer.search(workplacePosition, curMarkerLngLat, function(status, result) {
                    // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
                    if (status === 'complete') {
                        console.log('绘制公交路线完成')
                    } else {
                        console.log('获取公交数据失败：' + result)
                    }
                });
                break;
            case 'walk':
                amapTransfer = new AMap.Walking(options);

                amapTransfer.search(workplacePosition, curMarkerLngLat, function(status, result) {
                    if (status === 'complete') {
                        console.log('绘制步行路线完成')
                    } else {
                        console.log('获取步行数据失败：' + result)
                    }
                });
                break;

            default:
                alert('暂不支持的交通方式！')
        }

    }

    // 清空租房
    function delRentLocation() {
        if (rentMarkerArray)
            map.remove(rentMarkerArray);

        rentMarkerArray = [];
    }


    function loadRentLocation() {
        delRentLocation();
        var rent_locations = new Set();
        rentData.forEach(function(ele) {
            var address = [];
            address[0] = ele.title; // 简介
            address[1] = ele.location; // 位置
            address[2] = ele.url; // 详情url
            address[3] = ele.price; // 每月租金
            address[4] = ele.img_url; // 简略图

            addMarkerByAddress(address);
        })
        $("#btn_submit").removeAttr("disabled");
    }
});

// 
//